<template>
<view>
<view :style="topheight + ';background: #fff;'"></view>
<!-- 自定义头部 -->
<view class="head">
  <view @tap="toMine" class="headleft" style="width:70rpx;">
    <!-- <navigator url="../../pages/mine/mine" open-type="switchTab"> -->
      <image src="/static/remao_shop/img/arrow_left.png"></image>
    <!-- </navigator> -->
  </view>
  <view class="headright">我的订单</view>
  <image></image>
</view>
<!-- 顶部导航 -->
<view class="appraise">
  <scroll-view scroll-x="true" style=" white-space: nowrap; display: flex">
    <view v-for="(item, index) in navList" :key="index" @tap="getStatus" :id="'NAV' + index" class="appraise-title" :data-index="index">
      <view>
        <text :class="index == status ? 'active' : ''">{{item}}</text>
      </view>
    </view>
  </scroll-view>
</view>
<!-- 顶部导航End -->
<!-- 全部订单 -->
<view class="particulars-warp">
  <!-- 列表 -->
  <view v-for="(item, index) in orderList" :key="index" :hidden="orderList==''" class="particulars">
    <view class="bai"></view>
    <view v-for="(items, indexs) in item.item" :key="indexs" @tap="toOrderDetail" class="shopList" :data-index="index">
      <image :src="items.pic"></image>
      <view class="title">
        <view style="font-size:32rpx;color:#595959">{{items.name}}</view>
        <view>规格：{{items.pdt_desc}}</view>
        <view class="money">
          <text>x{{items.nums}}</text>
          <text style="font-size:30rpx;color:red">￥{{items.price}}</text>
        </view>
      </view>
    </view>
    <!-- 订单底部操作按钮组 -->
    <!-- 待支付 -->
    <view class="menu" v-if="item.status==10">
      <view class="menu-l">
        <text>需支付：</text>
        <text>￥{{item.total_price}}</text>
      </view>
      <view class="menu-r">
        <view @tap="showCloseOrder" :data-index="index" style="background:#fff;color:black;border:1rpx solid black">取消订单</view>
        <view @tap="toPay" :data-index="index">去支付</view>
      </view>
    </view>
    <!-- 待发货 -->
    <view class="menu" v-if="item.status==11">
      <view class="menu-l">
        <text>已支付：</text>
        <text>￥{{item.total_price}}</text>
      </view>
      <view class="menu-r">
        <text></text>
        <text style="color:red">订单待发货</text>
      </view>
    </view>
    <!-- 已发货 -->
    <view class="menu" v-if="item.status==6">
      <view class="menu-l">
        <text>已支付：</text>
        <text>￥{{item.total_price}}</text>
      </view>
      <view class="menu-r">
        <view @tap="toExpress" :data-index="index">查看物流</view>
        <view @tap="toGetShop" :data-index="index">确认收货</view>
      </view>
    </view>
    <!-- 待评价 -->
    <view class="menu" v-if="item.status==8">
      <view class="menu-l">
        <text>已支付：</text>
        <text>￥{{item.total_price}}</text>
      </view>
      <view class="menu-r">
        <text></text>
        <view @tap="toAppRaise" :data-index="index">去评价</view>
      </view>
    </view>
    <!-- 已完成 -->
    <view class="menu" v-if="item.status==4">
      <view class="menu-l">
        <text>已支付：</text>
        <text>￥{{item.total_price}}</text>
      </view>
      <view class="menu-r">
        <text></text>
        <text>订单已完成</text>
      </view>
    </view>
    <!-- 售后 -->
    <view class="menu" v-if="item.status==9">
      <view class="menu-l">
        <text>已支付：</text>
        <text>￥{{item.total_price}}</text>
      </view>
      <view class="menu-r">
        <text></text>
        <text>申请售后</text>
      </view>
    </view>
  </view>
  <view :hidden="orderList!=''" class="zanwu">
    <image src="/static/remao_shop/img/zanwu.png"></image>
    <view>暂无订单</view>
  </view>
  <!-- 列表End -->
</view>
<!-- 全部订单End -->
</view>
</template>

<script>
import api from "../../../api";
var app = getApp();

export default {
  data() {
    return {
      userId: '',
      // 选项卡
      navList: ["全部", "待付款", "待发货", "待收货", "待评价", "已完成", "售后"],
      status: 0,
      // 订单列表
      orderList: [],
      // 自定义导航头部适配
      topheight: '',
      requestShopId: '',
      // 支付参数--------------------
      openId: '',
      // 订单编号
      order_sn: '',
      // 支付类型
      payType: 2,
      // 支付金额
      payMoney: '',
      goodsID: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    let openid = wx.getStorageSync("openid");
    this.setData({
      openId: openid,
      status: options.status,
      userId: options.userId
    });
    console.log(options.userId);
    this.userOrder(); // 自定义导航适配

    var num = wx.getSystemInfoSync()['statusBarHeight'];
    console.log(num);
    this.setData({
      topheight: 'height:' + num + 'px'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.userOrder();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  methods: {
    // 加载订单
    userOrder: function () {
      var openId = wx.getStorageSync("openid");
      var that = this;
      var params = '';

      if (that.status == 0) {
        //全部
        params = 0;
      } else if (that.status == 1) {
        //待付款
        params = 10;
      } else if (that.status == 2) {
        //待发货
        params = 11;
      } else if (that.status == 3) {
        //待收货
        params = 6;
      } else if (that.status == 4) {
        //待评价
        params = 8;
      } else if (that.status == 5) {
        //已完成
        params = 4;
      } else if (that.status == 6) {
        //售后，已隐藏
        params = 9;
      }

      app.globalData.request({
        url: api.fyz.orderList,
        data: {
          uid: that.userId,
          // uid:10107,
          status: params
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          var oderList = res.order_list,
              item = [];

          for (var i = 0; i < oderList.length; i++) {
            for (var j = 0; j < oderList[i].item.length; j++) {
              item.push(oderList[i].item[j].goods_id);
            }
          }

          console.log(item);
          this.setData({
            goodsID: item,
            orderList: oderList
          });
        },
        fail: function (res) {//失败后的逻辑
        }
      });
    },

    // 选项卡
    getStatus(e) {
      console.log(e.currentTarget.dataset.index);
      this.setData({
        status: e.currentTarget.dataset.index // hidden: false

      });
      this.userOrder();
    },

    // 回到个人中心
    toMine: function () {
      wx.reLaunch({
        url: '../../pages/mine/mine'
      });
    },
    // 跳转订单详情
    toOrderDetail: function (e) {
      let that = this;
      console.log(e.currentTarget.dataset.index);
      let index = e.currentTarget.dataset.index;
      console.log(that.orderList[index].order_sn);

      if (that.status == '6' || that.orderList[index].status == "9") {
        wx.navigateTo({
          url: '../../packageC/aftersale/aftersale?order_sn=' + that.orderList[index].order_sn + '&userId=' + that.userId + '&orderId=' + that.orderList[index].order_id
        });
      } else {
        wx.navigateTo({
          url: '../../packageA/orderdetail/orderdetail?order_sn=' + that.orderList[index].order_sn + '&userId=' + that.userId
        });
      }
    },
    // 取消订单
    showCloseOrder: function (e) {
      let that = this; // console.log(e.currentTarget.dataset.index)

      let index = e.currentTarget.dataset.index;
      wx.showModal({
        title: '提示',
        content: '订单还未付款，确定要取消吗',
        cancelText: '取消订单',
        confirmText: '再考虑下',

        success(res) {
          if (res.confirm) {
            return;
          } else if (res.cancel) {
            app.globalData.request({
              url: api.fyz.delOrder,
              data: {
                order_id: that.orderList[index].order_id,
                uid: that.userId,
                reason_id: 1
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },
              method: 'POST',
              success: res => {
                console.log(res);

                if (res.status == 1) {
                  wx.showToast({
                    title: res.msg,
                    duration: 1000
                  });
                  setTimeout(function () {
                    that.userOrder();
                  }, 1000);
                }
              },
              fail: function (res) {//失败后的逻辑
              }
            });
          }
        }

      }); // this.setData({
      //   isShow:!that.data.isShow
      // })
    },
    //去评价
    toAppRaise: function (e) {
      let that = this;
      let index = e.currentTarget.dataset.index;
      var id = this.goodsID;
      console.log(id);
      wx.navigateTo({
        url: '../../packageA/appraise/appraise?userId=' + that.userId + '&index=' + index
      });
    },
    //确认收货
    toGetShop: function (e) {
      let that = this;
      let a = e.currentTarget.dataset.index;
      console.log();
      wx.showModal({
        content: '您确定要收货吗',
        confirmText: '拿到货物',
        cancelText: '还未拿到',

        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
            app.globalData.request({
              url: api.fyz.confirmShop,
              data: {
                uid: that.userId,
                order_id: that.orderList[a].order_id
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded' // 默认值

              },
              method: 'POST',
              success: res => {
                console.log(res);

                if (res.status == 1) {
                  wx.showToast({
                    title: '收货成功',
                    duration: 1000
                  });
                  setTimeout(function () {
                    that.userOrder();
                  }, 1000);
                }
              },
              fail: function (res) {//失败后的逻辑
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
            return;
          }
        }

      });
    },
    // 去支付
    toPay: function (e) {
      console.log(e.currentTarget.dataset.index);
      let index = e.currentTarget.dataset.index;
      this.setData({
        order_sn: this.orderList[index].order_sn,
        payMoney: this.orderList[index].total_price
      }); // 吊起微信支付

      this.weixinPayMoney(); // wx.navigateTo({
      //   url: '../../packageA/pay/pay?order=' + this.data.orderList[index].order_sn + '&type=2&money=' + this.data.orderList[index].total_price + '&userId=' + this.data.userId
      // })
    },

    // 微信支付
    weixinPayMoney() {
      var _that = this; // console.log(_that.data.order)
      // console.log(_that.data.type)
      // console.log(_that.data.payMoney)


      app.globalData.request({
        url: api.fyz.weixinPay,
        data: {
          type: _that.payType,
          pay_sn: _that.order_sn,
          money: _that.payMoney,
          openid: _that.openId
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值

        },
        method: 'POST',
        success: res => {
          console.log(res);
          var prepayid = res.ioswx_config.prepayid,
              osn = res.osn;
          console.log('支付id:', prepayid); //  付款成功

          if (res.status == 1) {
            wx.requestPayment({
              appId: res.weixin_config.appid,
              nonceStr: res.weixin_config.nonce_str,
              package: 'prepay_id=' + res.weixin_config.prepay_id,
              signType: 'MD5',
              timeStamp: res.weixin_config.timestamp,
              paySign: res.weixin_config.sign,
              success: function (res1) {
                wx.getStorage({
                  key: 'userId',
                  success: function (aaa) {
                    console.log(aaa.data);
                    var open = aaa.data;
                    console.log(open);
                    app.globalData.request({
                      url: api.gzSea.message,
                      //仅为示例，并非真实的接口地址
                      data: {
                        sole: prepayid,
                        order_sn: osn,
                        user_id: open
                      },
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded' // 默认值

                      },

                      success(res) {
                        console.log(res);
                      }

                    });
                  }
                }); //  更新订单状态

                app.globalData.request({
                  url: api.fyz.updataOrder,
                  data: {
                    user_id: _that.userId,
                    order_sn: _that.order_sn,
                    payment_id: 2
                  },
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值

                  },
                  method: 'POST',
                  success: res => {
                    console.log(res);

                    if (res.status == 1) {
                      console.log(_that.userId);

                      _that.userOrder(); // wx.redirectTo({
                      //   url: '../../packageB/order/order?status=0&userId=' + _that.data.userId,
                      // })
                      // wx.removeStorageSync('couponId')

                    } else {
                      wx.showToast({
                        title: res.msg,
                        duration: 1000
                      });
                    }
                  }
                });
              },
              fail: function (res2) {
                wx.showToast({
                  title: '支付失败，请重新支付',
                  duration: 1000
                });
              }
            });
          }
        },
        fail: function (ret) {
          console.log(ret);
        },
        complete: function (reb) {
          console.log(reb);
        }
      });
    },

    //查看物流
    toExpress: function (e) {
      console.log(e);
      var index = e.currentTarget.dataset.index,
          id = this.orderList[index].order_sn;
      wx.navigateTo({
        url: '../../packageC/express/express?sn=' + id
      });
    }
  }
};
</script>
<style>
@import "./order.css";
</style>